package com.qianfeng.pay01;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.qianfeng.pay01.config.AlixId;
import com.qianfeng.pay01.config.BaseHelper;
import com.qianfeng.pay01.config.MobileSecurePayHelper;
import com.qianfeng.pay01.config.MobileSecurePayer;
import com.qianfeng.pay01.config.PartnerConfig;
import com.qianfeng.pay01.config.ResultChecker;
import com.qianfeng.pay01.config.Rsa;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    ArrayList<Products.ProductDetail> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.mainListView);
        list = new Products().retrieveProductInfo();
        listView.setAdapter(new ProductListAdapter(this,list));
        listView.setOnItemClickListener(this);
    }
    ///
    String getSignType() {
        String getSignType = "sign_type=" + "\"" + "RSA" + "\"";
        return getSignType;
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Products.ProductDetail detail = list.get(position);
        MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
        boolean isMobile_spExist = mspHelper.detectMobile_sp();
        if (!isMobile_spExist)
            return;
        if (!checkInfo()) {
            BaseHelper
                    .showDialog(
                            this,
                            "提示",
                            "缺少partner或者seller，请在src/com/alipay/android/appDemo4/PartnerConfig.java中增加。",
                            R.drawable.infoicon);
            return;
        }
        String orderInfo = getOrderInfo(position);
        // 这里根据签名方式对订单信息进行签名
        String signType = getSignType();
        String strsign = sign(signType, orderInfo);

        // 对签名进行编码
        strsign = URLEncoder.encode(strsign);
        String info = orderInfo + "&sign=" + "\"" + strsign + "\"" + "&"
                + getSignType();
        Log.v("orderInfo:", info);
        // start the pay.
        // 调用pay方法进行支付
        MobileSecurePayer msp = new MobileSecurePayer();
        boolean bRet = msp.pay(info, mHandler, AlixId.RQF_PAY, this);

    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            try {
                String strRet = (String) msg.obj;

                Log.e("", strRet);	// strRet范例：resultStatus={9000};memo={};result={partner="2088201564809153"&seller="2088201564809153"&out_trade_no="050917083121576"&subject="123456"&body="2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红"&total_fee="0.01"&notify_url="http://notify.java.jpxx.org/index.jsp"&success="true"&sign_type="RSA"&sign="d9pdkfy75G997NiPS1yZoYNCmtRbdOP0usZIMmKCCMVqbSG1P44ohvqMYRztrB6ErgEecIiPj9UldV5nSy9CrBVjV54rBGoT6VSUF/ufjJeCSuL510JwaRpHtRPeURS1LXnSrbwtdkDOktXubQKnIMg2W0PreT1mRXDSaeEECzc="}
                switch (msg.what) {
                    case AlixId.RQF_PAY: {

                        BaseHelper.log("", strRet);

                        // 处理交易结果
                        try {
                            // 获取交易状态码，具体状态代码请参看文档
                            String tradeStatus = "resultStatus={";
                            int imemoStart = strRet.indexOf("resultStatus=");
                            imemoStart += tradeStatus.length();
                            int imemoEnd = strRet.indexOf("};memo=");
                            tradeStatus = strRet.substring(imemoStart, imemoEnd);

                            //先验签通知
                            ResultChecker resultChecker = new ResultChecker(strRet);
                            int retVal = resultChecker.checkSign();
                            // 验签失败
                            if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
                                BaseHelper.showDialog(
                                        MainActivity.this,
                                        "提示",
                                        getResources().getString(
                                                R.string.check_sign_failed),
                                        android.R.drawable.ic_dialog_alert);
                            } else {// 验签成功。验签成功后再判断交易状态码
                                if(tradeStatus.equals("9000"))//判断交易状态码，只有9000表示交易成功
                                    BaseHelper.showDialog(MainActivity.this, "提示","支付成功。交易状态码："+tradeStatus, R.drawable.infoicon);
                                else
                                    BaseHelper.showDialog(MainActivity.this, "提示", "支付失败。交易状态码:"
                                            + tradeStatus, R.drawable.infoicon);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            BaseHelper.showDialog(MainActivity.this, "提示", strRet,
                                    R.drawable.infoicon);
                        }
                    }
                    break;
                }

                super.handleMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    public static class AlixOnCancelListener implements
            DialogInterface.OnCancelListener {
        Activity mcontext;

        public AlixOnCancelListener(Activity context) {
            mcontext = context;
        }

        public void onCancel(DialogInterface dialog) {
            mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
        }
    }
    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param signType
     *            签名方式
     * @param content
     *            待签名订单信息
     * @return
     */
    String sign(String signType, String content) {
        return Rsa.sign(content, PartnerConfig.PRIVATE);
    }

    /**
     * get the out_trade_no for an order. 获取外部订单号
     *
     * @return
     */
    String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
        Date date = new Date();
        String strKey = format.format(date);

        java.util.Random r = new java.util.Random();
        strKey = strKey + r.nextInt();
        strKey = strKey.substring(0, 15);
        return strKey;
    }
    /**
     * check some info.the partner,seller etc. 检测配置信息
     * partnerid商户id，seller收款帐号不能为空
     *
     * @return
     */
    String getOrderInfo(int position) {
        String strOrderInfo = "partner=" + "\"" + PartnerConfig.DEFAULT_PARTNER + "\"";
        strOrderInfo += "&";
        strOrderInfo += "seller=" + "\"" + PartnerConfig.DEFAULT_SELLER + "\"";
        strOrderInfo += "&";
        strOrderInfo += "out_trade_no=" + "\"" + getOutTradeNo() + "\"";
        strOrderInfo += "&";
        strOrderInfo += "subject=" + "\"" + list.get(position).subject
                + "\"";
        strOrderInfo += "&";
        strOrderInfo += "body=" + "\"" + list.get(position).body + "\"";
        strOrderInfo += "&";
        strOrderInfo += "total_fee=" + "\""
                + list.get(position).price + "\"";
        strOrderInfo += "&";
        strOrderInfo += "notify_url=" + "\""
                + "http://notify.java.jpxx.org/index.jsp" + "\"";

        return strOrderInfo;
    }

    private boolean checkInfo() {
        String partner = PartnerConfig.DEFAULT_PARTNER;
        String seller = PartnerConfig.DEFAULT_SELLER;
        if (partner == null || partner.length() <= 0 || seller == null
                || seller.length() <= 0)
            return false;

        return true;
    }
}
